package com.luomuchen.redis;

import redis.clients.jedis.Jedis;

import java.util.Random;

public class Demo {
    public static void main(String[] args) {
        verifyCode("1231221321");
        //getRedisCode("1231221321","441295");
    }
    //获取验证码
    public static String getCode(){
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            int i1 = random.nextInt(10);
            code += i1;
        }
        return code;
    }
    //每个手机只能发送三次，验证码放到redis中，设置过期时间。
    public  static void verifyCode(String phone){
        //连接redis
        Jedis jedis = new Jedis("hadoop100",6379);
        //发送验证码次数
        String countKey = "VerifyCode" + phone +":count";
        //发送的验证码key
        String codeKey = "VerifyCode" + phone + "code";
        //查看今天已经发送了多少次验证码
        String count = jedis.get(countKey);
        if(count == null){
            jedis.setex(countKey, 24 * 60 * 60, "1");
        }
        else if(Integer.parseInt(count) <= 2){
            jedis.incr(countKey);
        } else if ("3".equals(count)) {
            System.out.println("今天发送的次数已经超过三次");
            jedis.close();
        }
        jedis.setex(codeKey, 120, getCode());
        jedis.close();
    }
    //比较验证码
    public static void getRedisCode(String phone, String code){
        Jedis jedis = new Jedis("hadoop100",6379);
        String codeKey = "VerifyCode" + phone + "code";
        String redisCode = jedis.get(codeKey);
        if(redisCode.equals(code)){
            System.out.println("成功");
        }
        else {
            System.out.println("失败");
        }
        jedis.close();
    }
}
